<template>
  <div class="weather-container">
    <a-card class="weather-card" :bordered="false">
      <template #title>
        <div class="page-header">
          <div class="title-section">
            <span class="emoji-title">🌦️</span>
            <span class="main-title">天气预报</span>
            <span class="emoji-title">☂️</span>
          </div>
        </div>
      </template>

      <!-- 搜索区域 -->
      <div class="search-section">
        <a-input-search
          v-model:value="cityName"
          placeholder="输入城市名称（如：北京、上海、广州）"
          enter-button="查询"
          size="large"
          :loading="loading"
          @search="searchWeather"
          allow-clear
        >
          <template #prefix>
            <environment-outlined />
          </template>
        </a-input-search>
      </div>

      <!-- 天气信息区域 -->
      <div v-if="weatherData" class="weather-info">
        <div class="city-info">
          <h2>{{ weatherData.city }} <span class="update-time">{{ currentTime }}</span></h2>
        </div>

        <div class="forecast-container">
          <a-row :gutter="[16, 16]">
            <a-col :xs="24" :sm="12" :md="8" v-for="(item, index) in weatherData.data" :key="index">
              <a-card
                class="forecast-card"
                :class="[getWeatherClass(item.weather), {'today-card': index === 0}]"
                :bordered="false"
              >
                <div class="forecast-header">
                  <div class="forecast-date">{{ item.date }}</div>
                  <div class="forecast-badge" :class="getAirQualityClass(item.air_quality)">
                    {{ item.air_quality }}
                  </div>
                </div>

                <div class="forecast-body">
                  <div class="weather-icon">{{ getWeatherEmoji(item.weather) }}</div>
                  <div class="weather-info">
                    <div class="weather-type">{{ item.weather }}</div>
                    <div class="temperature">{{ item.temperature }}</div>
                    <div class="wind">
                      <thunderbolt-outlined />
                      {{ item.wind }}
                    </div>
                  </div>
                </div>
              </a-card>
            </a-col>
          </a-row>
        </div>
      </div>

      <!-- 加载状态 -->
      <div v-if="loading" class="loading-container">
        <a-spin tip="正在获取天气数据...">
          <div class="loading-content">
            <cloud-outlined class="loading-icon" />
          </div>
        </a-spin>
      </div>

      <!-- 错误状态 -->
      <div v-if="error" class="error-container">
        <a-alert
          :message="error"
          type="error"
          show-icon
        />
      </div>

      <!-- 空状态 -->
      <div v-if="!weatherData && !loading && !error" class="empty-container">
        <a-empty description="请输入城市名称查询天气">
          <template #description>
            <span>支持查询全国城市、区县天气</span>
          </template>
        </a-empty>
      </div>

      <!-- 天气提示 -->
      <div v-if="weatherData" class="weather-tips">
        <a-alert
          :message="getWeatherTips(weatherData.data[0].weather)"
          type="info"
          show-icon
        />
      </div>
    </a-card>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue';
import { message } from 'ant-design-vue';
import axios from 'axios';
import {
  EnvironmentOutlined,
  CloudOutlined,
  ThunderboltOutlined
} from '@ant-design/icons-vue';

// 状态定义
const cityName = ref('广州');
const weatherData = ref(null);
const loading = ref(false);
const error = ref('');

// 获取当前时间
const currentTime = computed(() => {
  const now = new Date();
  const year = now.getFullYear();
  const month = String(now.getMonth() + 1).padStart(2, '0');
  const day = String(now.getDate()).padStart(2, '0');
  const hours = String(now.getHours()).padStart(2, '0');
  const minutes = String(now.getMinutes()).padStart(2, '0');

  return `${year}-${month}-${day} ${hours}:${minutes} 更新`;
});

// 搜索天气
const searchWeather = async (city) => {
  if (!city.trim()) {
    message.warning('请输入城市名称');
    return;
  }

  loading.value = true;
  error.value = '';

  try {
    // 直接使用API地址，不再使用CORS代理
    const apiUrl = `https://v2.api-m.com/api/weather?city=${encodeURIComponent(city.trim())}`;

    const response = await axios.get(apiUrl, {
      timeout: 10000
    });

    console.log('天气响应:', response);

    if (response.data && response.data.code === 200) {
      weatherData.value = response.data.data;
      message.success(`成功获取${weatherData.value.city}的天气信息`);
    } else {
      error.value = response.data.msg || '获取天气数据失败';
      message.error(error.value);
    }
  } catch (err) {
    console.error('获取天气失败:', err);
    error.value = `网络错误: ${err.message}`;
    message.error(error.value);
  } finally {
    loading.value = false;
  }
};

// 根据天气状况获取emoji
const getWeatherEmoji = (weather) => {
  if (weather.includes('晴')) return '☀️';
  if (weather.includes('多云')) return '⛅';
  if (weather.includes('阴')) return '☁️';
  if (weather.includes('雨') && weather.includes('雪')) return '🌨️';
  if (weather.includes('雷')) return '⛈️';
  if (weather.includes('雨')) {
    if (weather.includes('小')) return '🌦️';
    if (weather.includes('中')) return '🌧️';
    if (weather.includes('大') || weather.includes('暴')) return '💦';
    return '🌧️';
  }
  if (weather.includes('雪')) {
    if (weather.includes('小')) return '🌨️';
    if (weather.includes('大') || weather.includes('暴')) return '❄️';
    return '❄️';
  }
  if (weather.includes('雾') || weather.includes('霾')) return '🌫️';
  if (weather.includes('沙') || weather.includes('尘')) return '🏜️';

  return '🌈';
};

// 根据天气状况获取CSS类
const getWeatherClass = (weather) => {
  if (weather.includes('晴')) return 'sunny';
  if (weather.includes('多云')) return 'cloudy';
  if (weather.includes('阴')) return 'overcast';
  if (weather.includes('雨')) return 'rainy';
  if (weather.includes('雪')) return 'snowy';
  if (weather.includes('雾') || weather.includes('霾')) return 'foggy';

  return 'default';
};

// 根据空气质量获取CSS类
const getAirQualityClass = (quality) => {
  if (quality === '优') return 'excellent';
  if (quality === '良') return 'good';
  if (quality === '轻度') return 'moderate';
  if (quality === '中度') return 'unhealthy';
  if (quality === '重度') return 'very-unhealthy';
  if (quality === '严重') return 'hazardous';

  return 'default';
};

// 根据天气状况获取提示
const getWeatherTips = (weather) => {
  if (weather.includes('晴')) return '天气晴朗，适合户外活动，注意防晒哦！';
  if (weather.includes('多云')) return '天气多云，紫外线较弱，适合户外活动。';
  if (weather.includes('阴')) return '天气阴沉，紫外线弱，适合户外活动。';
  if (weather.includes('雨')) {
    if (weather.includes('小')) return '小雨天气，出门记得带伞！';
    if (weather.includes('中')) return '中雨天气，出行请带好雨具，小心路滑！';
    if (weather.includes('大') || weather.includes('暴')) return '大雨/暴雨天气，尽量减少外出，注意安全！';
    return '雨天出行，记得带伞！';
  }
  if (weather.includes('雪')) {
    if (weather.includes('小')) return '小雪天气，出门注意保暖，路面可能湿滑！';
    if (weather.includes('大') || weather.includes('暴')) return '大雪/暴雪天气，尽量减少外出，注意保暖和安全！';
    return '雪天出行，注意保暖和路面安全！';
  }
  if (weather.includes('雾') || weather.includes('霾')) return '能见度较低，出行注意安全，建议戴口罩！';
  if (weather.includes('沙') || weather.includes('尘')) return '沙尘天气，出门请戴好口罩，减少户外活动！';

  return '天气变化无常，出门请关注天气预报！';
};

// 组件挂载时自动查询默认城市天气
searchWeather(cityName.value);
</script>

<style scoped>
.weather-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.weather-card {
  border-radius: 16px;
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.1);
  overflow: hidden;
  background: linear-gradient(to bottom, #ffffff, #f9f9f9);
}

.page-header {
  text-align: center;
  margin-bottom: 16px;
}

.title-section {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 12px;
}

.emoji-title {
  font-size: 2rem;
}

.main-title {
  font-size: 2rem;
  font-weight: bold;
  background: linear-gradient(45deg, #13c2c2, #52c41a);
  -webkit-background-clip: text;
  background-clip: text;
  color: transparent;
}

/* 搜索区域 */
.search-section {
  margin-bottom: 24px;
}

/* 天气信息区域 */
.weather-info {
  margin-bottom: 24px;
}

.city-info {
  margin-bottom: 20px;
  text-align: center;
}

.city-info h2 {
  font-size: 1.8rem;
  color: #333;
  margin: 0;
}

.update-time {
  font-size: 0.9rem;
  color: #999;
  font-weight: normal;
  margin-left: 10px;
}

.forecast-container {
  margin-bottom: 20px;
}

.forecast-card {
  border-radius: 12px;
  overflow: hidden;
  transition: all 0.3s ease;
  height: 100%;
}

.forecast-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 10px 20px rgba(0, 0, 0, 0.1);
}

.forecast-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.forecast-date {
  font-size: 1.2rem;
  font-weight: bold;
}

.forecast-badge {
  padding: 4px 8px;
  border-radius: 12px;
  font-size: 0.8rem;
  font-weight: bold;
}

.forecast-body {
  display: flex;
  align-items: center;
}

.weather-icon {
  font-size: 3rem;
  margin-right: 16px;
}

.weather-info {
  flex: 1;
}

.weather-type {
  font-size: 1.2rem;
  font-weight: bold;
  margin-bottom: 4px;
}

.temperature {
  font-size: 1.5rem;
  margin-bottom: 8px;
}

.wind {
  display: flex;
  align-items: center;
  gap: 8px;
  color: #666;
}

/* 天气卡片样式 */
.sunny {
  background: linear-gradient(135deg, #ffe259, #ffa751);
  color: #664500;
}

.cloudy {
  background: linear-gradient(135deg, #d3d3d3, #a1c4fd);
  color: #333;
}

.overcast {
  background: linear-gradient(135deg, #bdc3c7, #2c3e50);
  color: #fff;
}

.rainy {
  background: linear-gradient(135deg, #5c6bc0, #3949ab);
  color: #fff;
}

.snowy {
  background: linear-gradient(135deg, #e6e6e6, #b3e5fc);
  color: #333;
}

.foggy {
  background: linear-gradient(135deg, #d7d2cc, #304352);
  color: #fff;
}

.default {
  background: linear-gradient(135deg, #a1c4fd, #c2e9fb);
  color: #333;
}

/* 今日天气卡片特殊样式 */
.today-card {
  box-shadow: 0 0 15px rgba(0, 0, 0, 0.2);
  position: relative;
}

.today-card::before {
  content: '今日';
  position: absolute;
  top: 10px;
  right: 10px;
  background-color: rgba(255, 255, 255, 0.8);
  color: #333;
  padding: 2px 8px;
  border-radius: 10px;
  font-size: 0.8rem;
  font-weight: bold;
}

/* 空气质量标签样式 */
.excellent {
  background-color: #52c41a;
  color: white;
}

.good {
  background-color: #fadb14;
  color: #333;
}

.moderate {
  background-color: #fa8c16;
  color: white;
}

.unhealthy {
  background-color: #f5222d;
  color: white;
}

.very-unhealthy {
  background-color: #722ed1;
  color: white;
}

.hazardous {
  background-color: #531dab;
  color: white;
}

/* 加载和错误状态 */
.loading-container, .error-container, .empty-container {
  padding: 40px 0;
  text-align: center;
}

.loading-content {
  padding: 50px 0;
}

.loading-icon {
  font-size: 3rem;
  color: #1890ff;
}

/* 天气提示 */
.weather-tips {
  margin-top: 20px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .weather-container {
    padding: 10px;
  }

  .main-title {
    font-size: 1.5rem;
  }

  .emoji-title {
    font-size: 1.5rem;
  }

  .city-info h2 {
    font-size: 1.4rem;
  }

  .update-time {
    display: block;
    margin-left: 0;
    margin-top: 5px;
  }

  .weather-icon {
    font-size: 2.5rem;
  }
}
</style>
